<?php

class Reportes_ComprasController extends Zend_Controller_Action
{

    /**
     * 
     * @var Zend_Auth_Storage_Interface
     */
    private $_user_info;
    /**
     * 
     * @var Zwei_Admin_Acl
     */
    private $_acl;
    /**
     * 
     * @var string
     */
    private $_page;

    public function init()
    {
        $this->_helper->layout()->disableLayout();
        if (Zend_Auth::getInstance()->hasIdentity()) {
            $this->_user_info = Zend_Auth::getInstance()->getStorage()->read();
            $this->_acl = new Zwei_Admin_Acl($this->_user_info->user_name);
            $this->_page = "reportes/compras";
            if (!$this->_acl->isUserAllowed($this->_page)) exit("<p>Acceso denegado a $this->_page</p>"); 
        } else {
            $this->_redirect('index/login');
        }
    }

	public function indexAction()
	{
		include_once ROOT_DIR."/libs/funciones.php";
		include_once ROOT_DIR."/classes/cliente-class.php";
		include_once ROOT_DIR."/classes/promociones-class.php";

		include_once ROOT_DIR."/classes/class_xml.php";


		//error_reporting(E_ALL);

		echo "<script src='".BASE_URL."js/funciones.js'></script>";
		// echo "<link rel=STYLESHEET type=text/css href=../css/calendar.css>";
		// echo "<script language=JavaScript src=../libs/simplecalendar.js type=text/javascript></script>";

		global $titleColor;
		global $blankColor;
		global $grayColor;

		global $_img_ok;

		$ok_image = $_img_ok;



		# Titulo
		echo "<h2>Promociones por Cliente</h2>";

		//$form = new HTML_Form('../pl_reportes/compras.php?consultar=Consultar&msisdn='.$_REQUEST["msisdn"],'post','myform');
		$form = new HTML_Form(BASE_URL.'reportes/compras','post','myform','ifrm_process');
		echo $form->returnStart()."\n";
		$fila=0;


		$tableAttrs = array('border' => "0",
                    'cellspacing' => "0",
                    'align' => "center",
                    'class' => "",
            'width' => "20%");

		$table = new HTML_Table($tableAttrs);
		$titleStyle = array('colspan' => "5");
		$blankStyle = array('colspan' => "5");
		$rowStyle   = array('align' => "left");

		//Buscar por MSISDN
		if (array_key_exists('msisdn', $_REQUEST))
		$req_msisdn=$_REQUEST["msisdn"];
		else
		$req_msisdn="";


		$row = array("<p CLASS=textoAzul>MSISDN</p>",
		$form->returnText("msisdn",$req_msisdn , 13, 15," dojoType=\"dijit.form.ValidationTextBox\"   RegExp=\"[\d]+\"  invalidMessage=\"Solo números\" required=\"true\"  "),
		$form->returnHidden('p',@$_REQUEST['p'],''),
		$form->returnSubmit("Consultar","consultar"),
         "",
		);



		$table->addRow($row,$rowStyle);
		$table->updateCellAttributes($fila, 1, array('valign' => "center"));


		$fila++;
		$table->display();

		echo "<br>";

		$editable = true;//Zwei_Admin_Acl::isActionAllowed( "EDIT" );

		if (array_key_exists('consultar', $_REQUEST))
		$req_consultar=$_REQUEST["consultar"];
		else
		$req_consultar="";


		if( $req_consultar== "Consultar" )
		{
			$cliente = new CLIENTE( $_REQUEST["msisdn"], "", "" );
			$compras = array();

			$compras = $cliente->getCompras();

			$requests = "?";
			foreach ($_REQUEST as $i => $v) {
				$requests .= "&$i=$v";
			}

			
			if (!isset($_REQUEST['norepost'])) {

				echo "<script>window.parent.cargarPanelCentral('/reportes/compras$requests&norepost=1');</script>";
			}

			$msisdn = $_REQUEST["msisdn"];

			if(count($compras) != 0)
			{
				echo "<p class=SUBT align='center'>Compras exitosas y fallidas</p>";
				#--- Parametros generales para las tablas usuarios y campaanas
				$tableUsuCamp = array('border' => "0",
                        'cellspacing' => "0",
                        'align' => "center",
                        'class' => "borde3",
                        'width' => "60%");

				$titleStyle = array('align' => "left");
				$blankStyle = array('align' => "left");
				$rowStyle   = array('align' => "left");
				#---



				$table = new HTML_Table($tableUsuCamp);
				if (array_key_exists("msg", $_REQUEST))
				$msg = $_REQUEST["msg"];
				else
				$msg = "&nbsp;";

				$msgStyle = array('align' => "center", 'bgcolor' => $blankColor);
				$msgRow = array("<font class='textoAzul'>$msg</font>");

				$row = array(
            "<label class=SUBT>Id Tx</label>",
            "<label class=SUBT>Promocion</label>",
            "<label class=SUBT>Estado</label>",
            "<label class=SUBT>Fecha Tx</label>",
				);

				if( $editable )
				$row[]="<label class=SUBT>Comprar</label>";
				$table->addRow($row,$titleStyle);

				$fila = 0;
				$i = 1;

				$table->updateCellAttributes($fila,0,array('width' => "15%"));
				$table->updateCellAttributes($fila,1,array('width' => "15%"));
				$table->updateCellAttributes($fila,2,array('width' => "15%"));
				$table->updateCellAttributes($fila,3,array('width' => "15%"));
				if($editable)
				$table->updateCellAttributes($fila,4,array('width' => "10%"));


				foreach ($compras as $key => $value)
				{
					$id_promo = $value[1];
					$comprar = $form->returnImage("activar", $ok_image, "border=0 alt='activar' title='Comprar Promocion' onClick='ConfirmarCompra(\"$id_promo\", \"$msisdn\")'");

					$row = array(
                "<label class=SUBT>{$value[0]}</label>",
                "<label class=textoAzul>{$value[1]}</label>", 
                "<label class=textoAzul>{$value[2]}</label>",
                "<label class=textoAzul>{$value[3]}</label>",

					);
					if ($editable){
						//$comprar2="<a href=\"\" \"onClick='ConfirmarCompra(\"$id_promo\", \"$msisdn\")'\"><img src=\"$ok_image\" border=0 alt=\"Comprar Promocion\"></img></a>";
						$comprar2 = $form->returnImage("activar", $ok_image, "border=0 alt='activar' title='Comprar Promocion' onClick='ConfirmarCompra(\"$id_promo\", \"$msisdn\")'");
						$row[]=$comprar2;
					}
					$fila++;
					if ($fila == 0 || ($fila%2) == 0)
					$table->addRow($row, $rowStyle);
					else
					$table->addRow($row, $blankStyle);
				}

				$table->display();
				echo "<br>";
				echo "<center><input type=\"button\" value=\"Exportar a Excel\" onClick=\"excelPromocionesCliente('{$_REQUEST['msisdn']}')\"></center>";
			}
			else
			echo "<br><br><p class=SUBT align=center>No existen registros</p>";

			echo "<br>";
			//////////////////////////////////////////////////////////////////
			if( $editable )
			{
				//Se obtiene todas las promociones
				$promociones = new PROMOCIONES();
				$promociones->get_all_promociones();

				//$promociones->get_all();
				$array_promo = array();
				foreach ($promociones->promociones as $key => $value)
				{
					$array_promo[$value] = $value;
				}

				echo "<p class=SUBT align='center'>Activar otra Promocion</p>";
				$tableAttrs2 = array('border' => "0",
                    'cellspacing' => "0",
                    'align' => "center",
                    'class' => "",
            'width' => "20%");

				$table = new HTML_Table($tableAttrs2);

				//Buscar Promo

				$row = array("<p CLASS=textoAzul>Promocion</p>",
				$form->returnSelect('id_promo', $array_promo, @$_REQUEST["id_promo"],1, '',false, " dojoType=\"dijit.form.FilteringSelect\""),
                "",
				$form->returnImage("activar2", $ok_image, "border=0 alt='activar' title='Comprar Promocion' onClick='ConfirmarCompra2(document.myform.id_promo.value, \"$msisdn\")'")
				);
				
				$table->addRow($row,$rowStyle);
				$table->updateCellAttributes($fila, 1, array('valign' => "center"));

				$fila++;
				$table->display();
			}

			echo $form->returnEnd()."\n";
		}
			
	}

	public function blAction()
	{
		if($_SERVER['REQUEST_METHOD'] == 'GET') {
			//$la_pe=$_REQUEST['p'];
			//echo "lape: ". $la_pe . "<br>";
			//echo "<script>window.parent.cargarPanelCentral('../{$_SERVER['REQUEST_URI']}') </script>";
			//echo $_SERVER['REQUEST_METHOD']."<br>";
		}

		include_once ROOT_DIR . "/classes/class_xml.php";

		//echo "<pre>"; print_r($_REQUEST);
		openlog("PROMOCIONES", LOG_PID | LOG_PERROR, LOG_LOCAL6);
		syslog(LOG_DEBUG, "COMPRA: (msisdn=". $_REQUEST["msisdn"] .")(id_promo=".$_REQUEST["id_promo"].")");
		$xmlcontent = "<?xml version='1.0'  encoding='ISO-8859-1'?>";
		$xmlcontent .= "<msg>";
		$xmlcontent .= "<header id_trans='1111' app='xml' user='web' passw='web' action='1'/>";
		$xmlcontent .= "<req>";
		$xmlcontent .= "<op>req_comp_promo</op>";
		$xmlcontent .= "<msisdn>".$_REQUEST["msisdn"]."</msisdn>";
		$xmlcontent .= "<idPromo>".$_REQUEST["id_promo"]."</idPromo>";
		$xmlcontent .= "</req>";
		$xmlcontent .= "</msg>";

		global $urlServerXML;
		$url = $urlServerXML;

		//echo $url;
		//sleep(1);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_VERBOSE, 0);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_POST, 1);
		//curl_setopt($ch, CURLOPT_PUT, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlcontent);

		$result = curl_exec($ch);
		//echo "Llega: [".$result."]<br>";

		if (curl_errno($ch))
		{
			syslog(LOG_DEBUG, "COMPRA: Error curl_errno");
			curl_close($ch);
			echo "<script  type='text/javascript'>
		                alert('No se pudo realizar la compra');
		                window.parent.cargarPanelCentral('reportes/compras?consultar=Consultar&msisdn=".$_REQUEST["msisdn"]."&norepost=1');
		
		              </script>";
		}
		else
		{
			curl_close($ch);
			if( $this->procesaXML($result) )
			{
				syslog(LOG_DEBUG, "COMPRA: Exitosa");
				echo "<script  type='text/javascript'>
		                alert('La compra fue realizada exitosamente');
		                window.parent.cargarPanelCentral('reportes/cons-online?consultar=Consultar&msisdn=".$_REQUEST["msisdn"]."&norepost=1');
		              </script>";
			}
			else
			{
				syslog(LOG_DEBUG, "COMPRA: Error");
				echo "<script  type='text/javascript'>
		                alert('No se pudo realizar la compra');
		                window.parent.cargarPanelCentral('reportes/compras?consultar=Consultar&msisdn=".$_REQUEST["msisdn"]."&norepost=1');
		              </script>";

			}
		}
		closelog();

	}

	function procesaXML($result)
	{
		$xml = new SimpleXMLElementExtended($result);
		if( !is_object($xml) )
		{
			echo "Error XML";
			return false;
		}

		//    echo "RESULT:  ".(string)$xml->resp->result;
		//    echo "STRRESULT:  ".(string)$xml->resp->strresult;

		if( (string)$xml->resp->result == 0 )
		return true;
		else
		return false;
	}


    public function excelAction()
    {
    	include_once ROOT_DIR. "/classes/cliente-class.php";
        $cliente = new CLIENTE( $_REQUEST["msisdn"], "", "" );
        $rowset = $cliente->getCompras();	
   	
        header('Content-type: application/vnd.ms-excel');
        header("Content-Disposition: attachment; filename=promociones_por_cliente.xls");
        header("Pragma: no-cache");
        header("Expires: 0");  
        
        $table = new Zwei_Utils_Table();
        echo $table->rowsetToHtml($rowset, array('ID Tx', 'Promocion', 'Estado', 'Fecha Tx'));
    }
	
}



